import Home from '@/pages/Home'
import Login from '@/pages/Login'
import Register from '@/pages/Register'
import Search from '@/pages/Search'
import Detail from '@/pages/Detail'
import AddCartSuccess from '@/pages/AddCartSuccess'
import ShopCart from '@/pages/ShopCart'
import vueRouter from 'vue-router'
import store from '@/store'
let originPush=vueRouter.prototype.push
let originReplace=vueRouter.prototype.replace
vueRouter.prototype.push=function(location,resolve,reject){
    if(resolve&&reject){
        originPush.call(this,location,resolve,reject)
    }else{
        originPush.call(this,location,()=>{},()=>{}) 
    }
}
vueRouter.prototype.replace=function(location,resolve,reject){
    if(resolve&&reject){
        originReplace.call(this,location,resolve,reject)
    }else{
        originReplace.call(this,location,()=>{},()=>{}) 
    }
}
 const router=new vueRouter({
    routes:[
        {
            path:'/shopcart',
            component:ShopCart,
            meta:{
                show:true
            }
        },
        {
            path:'/addcartsuccess',
            component:AddCartSuccess,
            meta:{
                show:true
            }
        },
        {
            path:'/home',
            component:Home,
            meta:{
                show:true
            }
        },
        {
            path:'/login',
            component:Login,
            meta:{
                show:false
            }
        },
        {
            path:'/register',
            component:Register,
            meta:{
                show:false
            }
        },
        {
            name:'ss',
            path:'/search/:keyword?',
            component:Search,
            meta:{
                show:true
            }
        },
        {
            path:'*',
            redirect:'/home'
        },
        {
          path:'/detail/:id?',
          component:Detail,
          meta:{
            show:true
        }
        }
    ],
    scrollBehavior(to,from,savedPosition){
        return {y:0}
    }
})
router.beforeEach(async (to,from,next)=>{
let token=store.state.user.token
if(token){
if(to.path=='/login'){
    next('/home')
}else{
    if(store.state.user.userInfo.name){
        next()
    }else{
        try{
         await this.$store.dispatch('getUserInfo')
        next()
        }catch(err){
        await this.$store.dispatch('userLogout')
         next('/login')
        }
    }
}
}else{
    next()
}
})
export default router